/*================================================================
*   Copyright (C) 2017 LiuYao. All rights reserved.
*   
*   Filename : graph.h
*   Author : LiuYao
*   Date : 2017-11-26
*   Description :  the Graph class, which manage all nodes, and 
*               provide the global singleton instance 
*
================================================================*/
#ifndef _GRAPH_H
#define _GRAPH_H

#include <vector>
#include "node.h"

using std::vector;

class Graph{
    private:
        // the global singleton instance
        static Graph * graph;
        // the nodes list 
        vector<Node*>* nodes_;
        // the mapping from var nodes to grad node
        unordered_map<Node*, Node*>* var_node2grad;
        bool isGradientConstructed;
        Graph();
        ~Graph();

        // the special class used to delete the singleton instance graph
        class Garbo{
            ~Garbo(){
                if(graph) 
                    delete graph;
            }
        };
        static Garbo garbo;

    public:
        void addNode(Node * );
        static Graph* getGraph();
        void constructGradientNodeds(Node* );
        unordered_map<Node*, unsigned int> getInNumOfGradNodesMap();
        unordered_map<Node*, unsigned int> getInNumOfNodesMap(Node* root);
        unordered_map<Node*, unsigned int> getOutNumOfGradNodesMap();
        unordered_map<Node*, unsigned int> getOutNumOfNodesMap(Node* root);
        unordered_map<Node*, Node*>* getGradOfVarNodeMap() { return var_node2grad; }
};
#endif
